#include <iostream>
#include <sys/types.h>
#include <cerrno>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string>
#include <string.h>
#include <netinet/in.h>
void Usage(std::string proc)
{
    std::cout << "Usage:\n\t" << proc << "server_ip server_port" << std::endl;
}
//./udp_client server_ip server_port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 0;
    }

    // 1.创建套接字
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        std::cerr << "socket create fail:" << errno << std::endl;
        return 1;
    }
    //你要给谁发
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(atoi(argv[2]));
    server.sin_addr.s_addr = inet_addr(argv[1]);
    //客户端使用随机端口，由操作系统自动绑定
    // 2.使用服务
    while (1)
    {
        // // 输入数据
        // std::string message;
        // std::cout << "输入#";
        // std::cin >> message;
        std::cout << "MyShell $";
        char line[1024];
        fgets(line, sizeof(line), stdin);

        sendto(sock, line, strlen(line), 0, (struct sockaddr *)&server, sizeof(server));

        struct sockaddr_in tmp;
        socklen_t len = sizeof(tmp);
        char buffer[1024];
        ssize_t cnt = recvfrom(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&tmp, &len);
        if (cnt > 0)
        {
            buffer[cnt] = 0;
            std::cout << "server echo#" << buffer << std::endl;
        }
    }
    return 0;
}